package com.hyts.standard.webflux.r2db.config;

import com.google.common.collect.Lists;
import com.hyts.standard.webflux.bean.po.UserPO;
import com.hyts.standard.webflux.r2db.dao.UsersDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author wayne
 * @version DbConfig,  2020/9/13
 */
//@Configuration
@Slf4j
public class DataSourceInitializeConfig {


//    @Bean
    public ApplicationRunner initDataSource(DatabaseClient client, UsersDao usersDao) {
        List<String> statements = loadSqlFrame();
//                Arrays.asList(
//                "DROP TABLE IF EXISTS USER;",
//                "CREATE TABLE IF NOT EXISTS USER" +
//                        " ( id SERIAL PRIMARY KEY, deleted int , status int,userName VARCHAR(100) NOT NULL, realName VARCHAR(100) NOT NULL, phone VARCHAR(100) NOT NULL birthday date;)");
        statements.forEach(sql -> executeSql(client,sql)
                .doOnSuccess(count -> log.info("Schema created, rows updated: {}", count))
                .doOnError(error -> log.error("got error : {}",error.getMessage(),error))
                .subscribe()
        );
        return args ->getUser().subscribe(user -> log.info("User saved: {}", user));
    }

    private Flux<UserPO> getUser() {
        return Flux.just(new UserPO(null, "John", "Doe"),
                new UserPO(null, "Jane", "Doe"));
    }



    private Mono<Integer> executeSql(DatabaseClient client, String sql) {
        return client.execute(sql).fetch().rowsUpdated();
    }


    public static List<String> loadSqlFrame() {
        ClassPathResource classPathResource  = new ClassPathResource("/r2db");
        List<String> dataList = Lists.newArrayList();
        try {
            Files.list(Paths.get(classPathResource.getFile().getAbsolutePath())).forEach(param->{
                try {
                    Stream<String> stream = Files.lines(param.toAbsolutePath());
                    StringBuilder stringBuilder = new StringBuilder();
                    stream.forEach(param2->{
                        if("----".equals(param2)){
                            if(stringBuilder.length() > 0){
                                dataList.add(stringBuilder.toString());
                            }
                            stringBuilder.delete(0,stringBuilder.length());
                        }
                        else if(param2.trim().length() > 0){
                            stringBuilder.append(param2).append("\n\r");
                        }
                        else{
                            log.info("find the blank info is ignore!");
                        }
                    });
                    dataList.add(stringBuilder.toString());
                } catch (IOException e) {
                    log.error("read the file is failure!",e);
                }
            });
            return dataList;
        } catch (IOException e) {
            e.printStackTrace();
            return dataList;
        }
    }

    public static void main(String[] args) {
        System.out.println(loadSqlFrame());;
    }
}
